/*
 * @Author: LVGRAPE
 * @LastEditors: LVGRAPE
 */
/*
    This file list all the functions for user to implement.
*/

#include "nd03_platform.h"
#include "rtthread.h"
#include <rtdevice.h>
#include "zino.h"
#define DBG_TAG "nd03_pla"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>
struct rt_i2c_bus_device* nd03_bus = RT_NULL;
#define ND03_I2C_BUS_ADDR 0X5B
#define ND03_I2C_BUS_NAME "i2c1"
int dn03_platform_init(void)
{
    rt_size_t ret = 0;
    nd03_bus = (struct rt_i2c_bus_device*)rt_device_find(ND03_I2C_BUS_NAME);
    if(nd03_bus != RT_NULL)
    {

        nd03_bus->retries=10;

        struct rt_i2c_msg msgs;
        msgs.addr = ND03_I2C_BUS_ADDR;
        msgs.flags = RT_I2C_WR;
        msgs.buf = NULL;
        msgs.len = 0;
        struct rt_i2c_bit_ops* ops = (struct rt_i2c_bit_ops*)nd03_bus->priv;
        ops->delay_us = 0;
        ret = rt_i2c_transfer(nd03_bus, &msgs, 1);
        if (ret == 1)
        {
            LOG_I("nd03 i2c init success\n");
            return RT_EOK;
        }
        else
        {
            LOG_E("nd03 i2c init fail, can't find address\n");
        }
        // LOG_D("Try:%s addr:0x%02X, ret:%d \n", i2cbusname, addr, ret);
    }
    else
    {
        LOG_E("Not found %s on system!\n", ND03_I2C_BUS_NAME);
    }
    return -RT_ERROR;
}
int32_t i2c_read_nbytes(uint8_t i2c_addr, uint16_t i2c_read_addr, uint8_t *i2c_read_data, uint8_t len)
{
    struct rt_i2c_msg msgs;
    uint8_t txAddr[2]={i2c_read_addr>>8, i2c_read_addr&0xff};
	msgs.addr = i2c_addr;
	msgs.buf = txAddr;
	msgs.len = 2;
	msgs.flags = RT_I2C_WR;
    if (rt_i2c_transfer(nd03_bus, &msgs, 1) != 1)
	{
		return -1;
    }
	msgs.addr = i2c_addr;
	msgs.buf = i2c_read_data;
	msgs.len = len;
	msgs.flags = RT_I2C_RD;
	// struct rt_i2c_bit_ops *ops = (struct rt_i2c_bit_ops *)vi_i2c_bus->priv;
	// ops->delay_us = 0;
	if (rt_i2c_transfer(nd03_bus, &msgs, 1) != 1)
	{
		return -2;
    }
    return 0;
}

int32_t i2c_write_nbytes(uint8_t i2c_addr, uint16_t i2c_write_addr, uint8_t *i2c_write_data, uint8_t len)
{
    //For user implement
    struct rt_i2c_msg msgs[2];
    uint8_t txAddr[2]={i2c_write_addr>>8, i2c_write_addr&0xff};
	msgs[0].addr = i2c_addr;
	msgs[0].buf = txAddr;
	msgs[0].len = 2;
	msgs[0].flags = RT_I2C_WR|RT_I2C_NO_STOP;

	msgs[1].addr = i2c_addr;
	msgs[1].buf = i2c_write_data;
	msgs[1].len = len;
	msgs[1].flags = RT_I2C_WR|RT_I2C_NO_START;
	// struct rt_i2c_bit_ops *ops = (struct rt_i2c_bit_ops *)vi_i2c_bus->priv;
	// ops->delay_us = 0;
	if (rt_i2c_transfer(nd03_bus, msgs, 2) != 2)
	{
		return -RT_ERROR;
    }
    return 0;
}


void delay_1ms(uint32_t count)
{
    rt_thread_mdelay(count);
    //For user implement
}

void delay_10us(uint32_t count)
{
    //For user implement
    volatile uint32_t len;
    for (; count > 0; count --)
        for (len = 0; len < 50; len++);
}


void set_xshut_pin_level(uint32_t level)
{
    //For user implement
}


